package com.xatz.scanner

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView.OnEditorActionListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.xatz.scanner.bean.CarBean
import com.xatz.scanner.databinding.ActivityDoormanReviewBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader


/**
 * author: tdq
 * date: 2021/7/22
 * description: 门卫复核
 */
class DoormanReviewActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var mBinding: ActivityDoormanReviewBinding

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    private var dialog: CustomDialog? = null

    private var carBean: CarBean? = null

    private val mLists = mutableListOf<CarBean>()

    private val arrayList = mutableListOf<String>()

    private var plantNumber = ""

    private var delivery = ""

    private lateinit var mAdapter: ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityDoormanReviewBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        mAdapter = ArrayAdapter(this, R.layout.spinner_select_car_number, R.id.tvCarNum, arrayList)
        mBinding.spCarNum.run {
            adapter = mAdapter
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    mBinding.tvOrder.text = mLists[position].delivery
                    plantNumber = mLists[position].plantNumber
                    delivery = mLists[position].delivery
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                }
            }
            dropDownVerticalOffset = 100
        }

        mBinding.etCount.setOnEditorActionListener(OnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_DONE) {
                hideKeyboard()
                return@OnEditorActionListener false
            }
            false
        })

        mBinding.btnClose.setOnClickListener(this)
        mBinding.btnFinish.setOnClickListener(this)
        mBinding.btnFinishTwo.setOnClickListener(this)

        getCarList()

        mBinding.srlLayout.setOnRefreshListener {
            getCarList()
        }

        dialog = CustomDialog(this)
    }

    private fun getCarList() {
        mLists.clear()
        arrayList.clear()
        mService.getCHPList().enqueue(object : Callback<String> {
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { parseXMLWithPull(it) }
                    if (mLists.isNotEmpty()) {
                        mLists.forEach { arrayList.add(it.plantNumber) }
                    }
                }
                mBinding.srlLayout.isRefreshing = false
                mAdapter.notifyDataSetChanged()
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
                mBinding.srlLayout.isRefreshing = false
                Timber.e(t)
            }

        })
    }

    private fun parseXMLWithPull(xmlData: String) {
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "v_mes_plate_number" -> {
                                carBean = CarBean("", "")
                            }
                            "c_plate_number" -> carBean?.plantNumber = xmlPullParser.nextText()
                            "c_delivery" -> carBean?.delivery = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("v_mes_plate_number" == xmlPullParser.name) {
                            carBean?.let { mLists.add(it) }
                            carBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btnFinish, R.id.btnFinishTwo -> {
                val count = mBinding.etCount.text.toString()

                val userAccount =
                    getSharedPreferences(Constant.configName, Context.MODE_PRIVATE)
                        .getString(Constant.userAccount, "").toString()

                if (plantNumber.isBlank()) {
                    if (dialog?.isShowing == false) {
                        dialog?.contextText = "请选择车牌号!"
                        dialog?.showDialog()
                    }
                    return
                }

                if (count.isBlank()) {
                    if (dialog?.isShowing == false) {
                        dialog?.contextText = "请输入复核数量!"
                        dialog?.showDialog()
                    }
                    return
                }

                if (count.toDouble() <= 0) {
                    if (dialog?.isShowing == false) {
                        dialog?.contextText = "复核数量必须是大于零的数字!"
                        dialog?.showDialog()
                    }
                    return
                }

                mService.mWFHComplete(delivery, plantNumber, count, userAccount)
                    .enqueue(object : Callback<String> {
                        override fun onResponse(call: Call<String>, response: Response<String>) {
                            if (response.isSuccessful) {
                                if (dialog?.isShowing == false) {
                                    dialog?.contextText = "操作成功"
                                    dialog?.showDialog()
                                }
                                mBinding.etCount.text = Editable.Factory.getInstance().newEditable("0")
                                mBinding.tvOrder.text = ""
                                plantNumber = ""
                                delivery = ""
                                getCarList()
                            } else {
                                response.errorBody()?.string()?.let {
                                    if (dialog?.isShowing == false) {
                                        dialog?.contextText = it
                                        dialog?.showDialog()
                                    }
                                }
                            }
                        }

                        override fun onFailure(call: Call<String>, t: Throwable) {
                            Timber.e(t)
                        }

                    })
            }
            R.id.btnClose -> finish()
        }
    }
}